<?php

/**
 * @author Rizky Tahara Shita
 * @website http://tahara.web.id
 * @email rizky.tahara@gmail.com
 * @copyright b'IT Cyber Solution
 */

class M_viewlist extends BZ_Model
{
	public $return_recursive;
	public $recursive_group;

	function __construct()
	{
		parent::__construct();

		$this->return_recursive[0] = '/root';
		$this->recursive_group = '';
	}


/**
 * @section View List
 * @description generate view list table of data from database
 */

	/**
	 * @function _action_delete
	 * @description generate the delete action in view list
	 */
	function _action_delete
		(
			$prm_url = '', $prm_image_path = ''
			, $prm_key = '', $prm_ajax_type = ''
			, $prm_css_form = 'frm_header', $prm_css_process = 'process', $prm_css_message_error = 'error_message'
		)
	{
		$image_attr = array
			(
				'src' => site_url($prm_image_path.'/error.png')
				, 'border' => 0, 'width' => 16, 'height' => 16
				, 'alt' => $this->lang->line('tooltips_delete')
			);

		if (trim($prm_ajax_type) != '') $prm_ajax_type = '_'.$prm_ajax_type;

		$return_value = '<a href="javascript: js_form_delete_confirm(\''.site_url($prm_url).'\', \'ajx'.$prm_ajax_type.'_\', \'delete\', \''.$prm_key.'\', \'#'.$prm_css_form.'\', \'#'.$prm_css_process.'\', \'#'.$prm_css_message_error.'\');" class="border_no" title="'.$this->lang->line('tooltips_delete').'">'.img($image_attr, TRUE).'</a>';

		return $return_value;
	}


	/**
	 * @function _action_download
	 * @description generate the download action in view list
	 */
	function _action_download($prm_image_path = '', $prm_file = '')
	{
		$image_attr = array
			(
				'src' => site_url($prm_image_path.'/download.png')
				, 'border' => 0
				, 'width' => 16, 'height' => 16
				, 'alt' => $this->lang->line('tooltips_download')
			);

		$return_value = '<a href="'.site_url($prm_file).'" class="border_no" title="'.$this->lang->line('tooltips_download').'" target="_blank">'.img($image_attr, TRUE).'</a>';

		return $return_value;
	}


	/**
	 * @function generate
	 * @description generate the view list of data
	 */
	function generate
		(
			$prm_dbase = 'db_default'
			, $prm_fields = '', $prm_fields_primary = array('SHOW' => FALSE, 'DATA' => array()), $prm_fields_edit_name = '', $prm_fields_order = '2, 1'
			, $prm_table_name = '', $prm_table_where = '', $prm_query_or_like = ''
			, $prm_segment_create = ''
			, $prm_records_limit = 20
			, $prm_segment_name = 'form'

			, $prm_link_edit_use = TRUE
			, $prm_link_delete_use = TRUE
			, $prm_link_first_column = 'none' //values: none, auto-numbers or checkbox
			, $prm_link_print_use = 'FALSE' //values: TRUE, FALSE, HISTORY_NO
			, $prm_link_download_use = FALSE, $prm_link_download_path = ''

			, $prm_recursive_use = FALSE
			, $prm_recursive_parent_fields = 'parent_id'
			, $prm_recursive_as_combo = FALSE
			, $prm_recursive_parent_id = 0, $prm_recursive_level = 0
			, $prm_recursive_delimiter = '&mdash;', $prm_recursive_root_use = FALSE

			, $prm_recursive_group_use = FALSE

			, $prm_query_special = FALSE
		)
	{
		/**
		 * @description init the variables
		 */
		$variables = array
			(
				'IMAGE' => array
					(
						'PATH' => 'themes/'.$this->web_data['BISKITZ']['SETTINGS']['BISKITZ_THEME_ADMIN'].'/images/icons'
					)
			);

		/**
		 * @description init the pagination
		 */
		if ($prm_records_limit != 0)
		{
			$prm_page_current = $this->pagination->cur_page - 1;
			if ($prm_page_current < 0) $prm_page_current = 0;

		}
		else
		{
			$prm_page_current = 0;
		}


		/**
		 * @description let's query the data
		 */
		$use_db = $this->{$prm_dbase};
		$use_db->select($prm_fields, FALSE);

		/**
		 * @description need the join clause?
		 */
		if (is_array($prm_table_name))
		{
			/**
			 * @description $prm_table_name as array? then proceed to use JOIN.
			 * 								with index array are: $prm_table_name['SOURCE'], $prm_table_name['JOIN'][]['TABLE'], $prm_table_name['JOIN'][]['KEYS'], $prm_table_name['JOIN'][]['TYPE']
			 */
			$use_db->from($prm_table_name['SOURCE']);
			foreach ($prm_table_name['JOIN'] as $table_join)
			{
				$use_db->join($table_join['TABLE'], $table_join['KEYS'], $table_join['TYPE']);
			}
		}

		/**
		 * @description need the where clause?
		 * 								wanna use recursif with where parameters? pass the $prm_table_where as array()
		 */
		if (is_array($prm_table_where) OR trim($prm_table_where) != '')
		{
			$use_db->where
				(
					($prm_recursive_use == TRUE) ?
						array_merge
						(
							array($prm_recursive_parent_fields => $prm_recursive_parent_id)
							, $prm_table_where
						)
						: $prm_table_where
					, NULL
					, ($prm_query_special == TRUE) ? FALSE : NULL
				);
		}

		/**
		 * @description need the or_like clause?
		 */
		if (is_array($prm_query_or_like))
		{
			$use_db->or_like($prm_query_or_like);
		}

		/**
		 * @description order the result
		 */
		$use_db->order_by($prm_fields_order);

		/**
		 * @description need to limit the result?
		 */
		if ($prm_records_limit != 0)
		{
			$use_db->limit($prm_records_limit, ($prm_page_current * $prm_records_limit));
		}


		is_array($prm_table_name)
			? $query = $use_db->get()
			: $query = $use_db->get($prm_table_name);

		switch ($prm_recursive_use)
		{
			case TRUE:
				$recursive_dash = str_repeat($prm_recursive_delimiter, $prm_recursive_level);
				switch ($prm_recursive_root_use)
				{
					case FALSE:
						unset($this->return_recursive[0]);
						break;
				}
				break;

			case FALSE:
				$i = 0;
				$recursive_dash = '';
				$this->return_recursive = '';
				break;
		}

		if ($query->num_rows() > 0)
		{
			$fields_type = $query->field_data();

			foreach ($query->result() as $rows)
			{
				switch ($prm_recursive_use)
				{
					case TRUE:
						$i = $rows->id;
						break;
				}
				$j = 0;

				/**
				 * @description generate the keys
				 */
				$key_string = '';
				foreach ($prm_fields_primary['DATA'] as $fields_idx => $fields_primary)
				{
					if ($fields_idx != 0) $key_string .= '/';
					$key_string .= $rows->$fields_primary;
				} // TODO: bukannya bisa pake implode aja atau pake function-nya ci aja (mungkin: $this->uri->assoc_to_uri() )??? //////// SHOULD OPTIMZE THIS ???!!!!


				/**
				 * @description first column, should it be auto-numbers, checkbox or none ?
				 */
				switch ($prm_link_first_column)
				{
					case 'auto-numbers':
						$this->return_recursive[$i][$j] = ($prm_page_current * $prm_records_limit) + 1 + $i;
						break;

					case 'checkbox':
						$checkbox_data = array
							(
								'name' => 'txtcheck['.$i.']'
								, 'id' => 'chk'.$i
								//~ , 'value' => implode('/', $key_string)
								, 'value' => $key_string
							);

						$this->return_recursive[$i][$j] = form_checkbox($checkbox_data);
						break;
				}
				$j++;


				/**
				 * @description need the call of user's call_functions javascript when edit data row?
				 */
				if (is_array($prm_segment_name))
				{
					$edit_link = $prm_segment_name['JS_FUNCTION_NAME'] . '(' . $prm_segment_name['JS_FUNCTION_PARAMETERS'] . ', "' . $key_string . '")';
				}
				else
				{
					$edit_link = site_url($prm_segment_create . '/' . $prm_segment_name . '/' . $key_string);
					if ($prm_link_print_use != 'TRUE') $edit_link = 'js_common_link("' . $edit_link . '")';
				}

				/**
				 * @description iterate the fields to be shown
				 */
				foreach ($fields_type as $field)
				{
					switch ($field->type)
					{
						case 'int':
						case 'real':
							/**
							 * @description numeric type? set to right alignment
							 */
							$field_data = $rows->{$field->name};

							if ( ! $field->primary_key)
							{
								(strpos($field_data, '.') === FALSE) ? $field_decimal_length = 0 : $field_decimal_length = 2;
								$field_data = '<div align="right">'.number_format($field_data, $field_decimal_length, ',', '.').'</div>';
							}
							break;

						default:
							$field_data = htmlentities(substr(strip_tags($rows->{$field->name}), 0, 100));
							break;
					}


					if ($field->name == $prm_fields_edit_name)
					{
						switch ($prm_link_edit_use)
						{
							case TRUE:
								switch ($prm_link_print_use)
								{
									case 'TRUE':
										/**
										 * @description show print pop up when clicked the links
										 */
										$link_attr = array
											(
												'HREF' => '#'
												, 'ONCLICK' => 'javascript: js_print_popup("'.$edit_link.'")'
												, 'TARGET' => 'biskitZ_report'
												, 'TITLE' => $this->lang->line('tooltips_print')
											);
										break;

									case 'HISTORY_NO':
										/**
										 * @description by pass the history. disable the back button functionality
										 */
										$link_attr = array
											(
												'HREF' => 'javascript: '.$edit_link
												, 'ONCLICK' => ''
												, 'TITLE' => $this->lang->line('tooltips_edit')
											);
										break;

									default:
										/**
										 * @description remember the history, so it can go back to prev history
										 */
										$link_attr = array
											(
												'HREF' => '#'
												, 'ONCLICK' => $edit_link
												, 'TITLE' => $this->lang->line('tooltips_edit')
											);
										break;
								}

								$this->return_recursive[$i][$j] = $recursive_dash . "<a href='".$link_attr['HREF'] . "' onClick='" . $link_attr['ONCLICK'] . "' title='"
									. $link_attr['TITLE'] . "'>" . htmlentities(substr(strip_tags($rows->{$prm_fields_edit_name}), 0, 100)) . "</a>";
								break;


							case FALSE:
								/**
								 * @description need return as combo? then return as 1 dimensional array
								 */
								switch ($prm_recursive_as_combo)
								{
									case TRUE:
										switch ($prm_recursive_group_use)
										{
											case TRUE:
												/**
												 * @description use group options ?
												 */
													/**
													 * @description check if there is any sub menu or not
													 */
													$data_sub_count = $this->M_database->total_rows
														(
															$prm_dbase
															, $prm_table_name
															, array($prm_recursive_parent_fields => $i)
														);

													if ($data_sub_count > 0)
													{
														$this->recursive_group = $recursive_dash.$field_data;
														$this->return_recursive[$recursive_dash.$field_data] = array();

													}
													else
													{
														$this->return_recursive[$this->recursive_group][$i] = $recursive_dash.$field_data;
													}
												break;


											default:
												$this->return_recursive[$i] = $recursive_dash.$field_data;
												break;
										}
										break;

									case FALSE:
										$this->return_recursive[$i][$j] = $recursive_dash.$field_data;
										break;
								}
								break;
						}


					}
					else
					{
						($prm_fields_primary['SHOW'])
							? $fields_to_show = $prm_fields_primary['SHOW']
							: $fields_to_show = ! in_array($field->name, $prm_fields_primary['DATA'], TRUE);

						if ($fields_to_show == TRUE)
						{
							/**
							 * @description need return as combo? return as 1 dimensional array
							 */
							switch ($prm_recursive_as_combo)
							{
								case TRUE:
									switch ($prm_recursive_group_use)
									{
										case TRUE:
											/**
											 * @description use group options ?
											 */
												/**
												 * @description check if there is any sub menu or not
												 */
												$data_sub_count = $this->M_database->total_rows
													(
														$prm_dbase
														, $prm_table_name
														, array($prm_recursive_parent_fields => $i)
													);

												if ($data_sub_count > 0)
												{
													$this->recursive_group = $recursive_dash.$field_data;
													$this->return_recursive[$recursive_dash.$field_data] = array();

												}
												else
												{
													$this->return_recursive[$this->recursive_group][$i] = $recursive_dash.$field_data;
												}
											break;


										default:
											$this->return_recursive[$i] = $recursive_dash.$field_data;
											break;
									}
									break;

								case FALSE:
									/**
									 * @description we need to hide fields with the "hidden__" prefix alias
									 *								the fields still exists, but NOT showing; ex: for reordering purpose
									 */
									if (substr($field->name, 0, 8) != 'hidden__')
									{
										$this->return_recursive[$i][$j] = $field_data;
									}
									break;
							}
						}
					}


					$j++;
				}


			/**
			 * @section COMMANDS
			 */

				/**
				 * @description need the download command?
				 */
				switch ($prm_link_download_use)
				{
					case TRUE:
						$this->return_recursive[$i][$j] = $this->_action_download($variables['IMAGE']['PATH'], $prm_link_download_path['DOWNLOAD_PATH'].'/'.$rows->{$prm_link_download_path['DOWNLOAD_FIELD'][0]});
						$j++;
						break;
				}


				/**
				 * @description delete command
				 */
				if (is_array($prm_link_delete_use))
				{
					/**
					 * @description $prm_link_delete_use as array? should have parameters needed to process a delete
					 */
					$this->return_recursive[$i][$j] = $this->_action_delete
						(
							$prm_segment_create, $variables['IMAGE']['PATH'], $key_string
							, $prm_link_delete_use['prm_ajax_type']
							, $prm_link_delete_use['prm_css_form'], $prm_link_delete_use['prm_css_process'], $prm_link_delete_use['prm_css_message_error']
						);
				}
				else
				{
					/**
					 * @description $prm_link_delete_use is not array? process regular delete
					 */
					switch ($prm_link_delete_use)
					{
						case TRUE:
							$this->return_recursive[$i][$j] = $this->_action_delete($prm_segment_create, $variables['IMAGE']['PATH'], $key_string);
							break;
					}
				}


				/**
				 * @description use the recursive?
				 */
				switch ($prm_recursive_use)
				{
					case TRUE:
						$this->generate
							(
								$prm_dbase
								, $prm_fields, $prm_fields_primary, $prm_fields_edit_name, $prm_fields_order
								, $prm_table_name, $prm_table_where, $prm_query_or_like
								, $prm_segment_create
								, $prm_records_limit
								, $prm_segment_name

								, $prm_link_edit_use
								, $prm_link_delete_use
								, $prm_link_first_column
								, $prm_link_print_use
								, $prm_link_download_use, $prm_link_download_path

								, $prm_recursive_use
								, $prm_recursive_parent_fields
								, $prm_recursive_as_combo
								, $rows->id, $prm_recursive_level + 1
								, $prm_recursive_delimiter, $prm_recursive_root_use

								, $prm_recursive_group_use

								, $prm_query_special
							);
						break;

					case FALSE:
						$i++;
						break;
				}


			}
		}


		$query->free_result();
		return $this->return_recursive;
	}



}

/** End of file m_viewlist.php */
/** Location: ./biskitz_mpc/biskitz/models/m_viewlist.php */
